import CryptoEs from 'crypto-es';

export interface EncryptionParams {
  key: string;
  iv: string;
}

export class Encryption {
  private key;
  private iv;

  constructor(opt: EncryptionParams) {
    const { key, iv } = opt;
    // 生成规则
    this.key = CryptoEs.enc.Utf8.parse(key);
    this.iv = CryptoEs.enc.Utf8.parse(iv);
  }

  get getOpt(): CryptoEs.lib.CipherCfg {
    return {
      mode: CryptoEs.mode.CBC as any,
      padding: CryptoEs.pad.Pkcs7,
      iv: this.iv,
    };
  }

  encryptByAES(str: string) {
    const encrypted = CryptoEs.AES.encrypt(str, this.key, this.getOpt);
    return encrypted.toString();
  }

  decryptByAES(str: string) {
    const decrypted = CryptoEs.AES.decrypt(str, this.key, this.getOpt);
    return decrypted.toString(CryptoEs.enc.Utf8);
  }
}

export default Encryption;
